<?php

class AutoUidModel
{
    private $femaleAuthKeyPrefix=   'FH/';
    private $autoUidKeyPrefix   =   'AU/';
    private $userLoginKeyPrefix =   'UL/';
    private $followKeyPrefix    =   'FI/';
    private $mobileCodeKeyPrefix=   'MBC/';
    private $emailCodeKeyPrefix=   'EMC/';
    private $userVipKeyPrefix   =   'UV/';
    private $diaryListCacheModel;
    private $userModel;
    private $userStatisticsModel;
    private $userMemberModel;
    private $followModel;
    private $followMeType       =   1;
    private $meFollowType       =   2;
    static public $_G = [];
    
    public function __construct(){
        $this->diaryListCacheModel  =   new DiaryListCacheModel();
        $this->userModel            =   new UserModel();
        $this->userStatisticsModel  =   new UserStatisticsModel();
        $this->userMemberModel      =   new UserMemberModel();
        $this->followModel          =   new FollowModel();
    }

    public function begin(){
        $key    =   $this->autoUidKeyPrefix. '0';
        return Storage::beginTransaction($key);
    }

    public function commit(){
        $key    =   $this->autoUidKeyPrefix. '0';
        return Storage::commitTransaction($key);
    }

    public function rollback(){
        $key    =   $this->autoUidKeyPrefix. '0';
        return Storage::rollbackTransaction($key);
    }

   public function checkUserFemaleAuth($info){	  
    	isset($info['uid']) && $uid = $info['uid'];
	if(empty($uid)){
		return false;
	}
	$femaleAuthInfo = $this->getFemaleAuthInfo($uid); 
	if(!empty($femaleAuthInfo) && $femaleAuthInfo['status']== 0){//已经认证
		return true;
	}
	return false;
    }
    
      //获取女生认证信息
    public function getFemaleAuthInfo ($uid) {
        // 1.判断
        if (empty($uid)) {
            AC::$errorNo = 'CMFA001';
            return false;
        }    
        // 2.设置key
        $key = $this->femaleAuthKeyPrefix. 0;
    
        // 3.条件
        $where = array('uid'=>$uid); 
    
        // 4.调用底层函数，获取数据
        $result =   Storage::getConditionData($key, $where);
    
        // 5.判断?
        return $result;
    }
    
    //添加认证消息
    public  function addFemaleAuth($femaleAuthData){
     
        $key         =   $this->femaleAuthKeyPrefix. 0;
       
        return Storage::addData($key, $femaleAuthData);
    }
    
    //更新认证消息
    public function  updateFemaleAuth($uid,$femaleAuthData){

        $key         =  $this->femaleAuthKeyPrefix. 0;
        $where=array('uid'=>$uid);
        
        $result=Storage::setConditionData($key, $femaleAuthData, $where);
        return $result;
    }
   
    public function initAutoUid($info)/*{{{*/
    {
        if (empty($info['account']) ||  empty($info['email'])   ||  ('' ==  $info['nickname']))
        {
            AC::$errorNo    =   'AUM001';
            return  FALSE;
        }

        $checkAccount   =   $this->checkAccount($info['account'], TRUE);
        if (!empty($checkAccount))  return  FALSE;

        $checkEmail     =   $this->checkEmail($info['email'], TRUE);
        if (!empty($checkEmail))    return  FALSE;

        if (!isset($info['registerDevice'])) $info['registerDevice'] = '';
        if (!isset($info['registerChannel'])) $info['registerChannel'] = '';
        
        $uid = $this->filterPrettyNumber($info);
        
        if ($uid === FALSE)
        {
            AC::$errorNo    =   'AUM004';
            return  FALSE;
        }
        return  $uid;
    }/*}}}*/
    
    public function initAutoUidData($info)/*{{{*/
    {
        $data   =   array(
                        'account'           =>  $info['account'],
                        'platform'          =>  'ffrj',
                        'nickname'          =>  $info['nickname'],
                        'email'             =>  $info['email'],
                        'registerDevice'    =>  $info['registerDevice'],
                        'registerChannel'   =>  $info['registerChannel'],
                        'deviceSN'          =>  $info['deviceSN'],
                        'registerTime'      =>  AC::SERVER_TIME,
                        'registerIP'        =>  UK::getClientIp(),
                    );
        isset($info['platform'])    &&  $data['platform']   =   $info['platform'];

        if (!empty($info['uid'])    &&  (AC::HOST_UID   ==  $info['uid']))
        {
            $data['uid']    =   $info['uid'];
        }
        $key    =   $this->autoUidKeyPrefix. $info['account'];
        $result =   Storage::addData($key, $data);
        
        if (empty($result))
        {
            AC::$errorNo    =   'AUM004';
            return  FALSE;
        }
        else
        {
            $data['uid']    =   $result;
        }
        return  $data['uid'];
    }/*}}}*/
    
    public function filterPrettyNumber($info)/*{{{*/
    {
        $uid = $this->initAutoUidData($info);
        if (FALSE === $uid) {
            return $uid;
        }

        $pretty =$this->isPrettyNumber($uid);
        if (FALSE === $pretty) {
            UK::saveLog('pretty_filter.log', date("Y-m-d H:i:s",time()).','.$uid.','."normal"."\n", TRUE);
            return $uid;
        }
        
       $pretty_user = "pink_".$uid;
       $data   =   array(
                    'account'           =>  $pretty_user,
                    'platform'          =>  'ffrj',
                    'nickname'          =>  $uid,
                    'email'             =>  $pretty_user.'@ffrj.net',
                    'registerDevice'    =>  $info['registerDevice'],
                    'registerChannel'   =>  "pink_pretty_system",
                    'deviceSN'          =>  "pink_pretty_system",
                    'registerTime'      =>  AC::SERVER_TIME,
                    'registerIP'        =>  UK::getClientIp(),
        );
        $key    =   $this->autoUidKeyPrefix. $info['account'];
        $where  =   array('uid' => $uid);
        $result =   Storage::setConditionData($key, $data, $where);
        UK::saveLog('pretty.log', date("Y-m-d H:i:s",time()).','.$uid.','.$pretty."\n", TRUE);

        return $this->filterPrettyNumber($info);
    }    

    private function isPrettyNumber($uid)/*{{{*/
    {
        $uid = intval($uid);
        if(preg_match('/[^\d]/',$uid)){
            return FALSE;
        }
        
        if(preg_match('/(?:(?:0(?=1)|1(?=2)|2(?=3)|3(?=4)|4(?=5)|5(?=6)|6(?=7)|7(?=8)|8(?=9)){4,}|(?:9(?=8)|8(?=7)|7(?=6)|6(?=5)|5(?=4)|4(?=3)|3(?=2)|2(?=1)|1(?=0)){4,})\d/i',$uid)){
            return  'ABCDE|EDCBA';
        }
        
        if(preg_match('/([\d])\1{3,}/i',$uid)){
            return  'AAAA';
        }
        
        if(preg_match('/([\d])\1{1,}([\d])\2{2,}/i',$uid)){
            return  'AABBB';
        }
        
        if(preg_match('/(([\d]){1,}([\d]){2,})\1{1,}/i',$uid)){
            return  'ABBABB';
        }
        
        if(preg_match('/(([\d]){1,}([\d]){1,})\1{2,}/i',$uid)){
            return  'ABABAB';
        }
        
        if(preg_match('/(20)([0-2])([1-9])((0[1-9])|(1[0-2]))(30|31|(2[0-9])|(1[0-9])|(0[1-9]))/i',$uid)){
            return  '00后生日号';
        }
        
        if(preg_match('/(19)([8-9])([1-9])((0[1-9])|(1[0-2]))(30|31|(2[0-9])|(1[0-9])|(0[1-9]))/i',$uid)){
            return  '80后生日号';
        }
        return FALSE;
    }

    public function getUserBaseInfo($info)/*{{{*/
    {
        if (empty($info['uid']) &&  empty($info['account']) &&  empty($info['email']))
        {
            AC::$errorNo    =   'AUM005';
            return  FALSE;
        }
 
        !empty($info['uid'])    &&  $where['uid']       =   $info['uid'];
        !empty($info['account'])&&  $where['account']   =   $info['account'];
        !empty($info['email'])  &&  $where['email']     =   $info['email'];
        $key    =   $this->autoUidKeyPrefix. 0;
        $result =   Storage::getConditionData($key, $where);
        if (empty($result['uid'])   ||  empty($result['account']))
        {
            AC::$errorNo    =   'AUM006';
            return  FALSE;
        }
        return $result;
    }/*}}}*/

    public function getAutoUidDetail($uid)
    {
        if (empty($uid)) return $uid;

        $key    =   $this->autoUidKeyPrefix. 0;
        $where  =   array('uid' => $uid);
        $result =   Storage::getConditionData($key, $where);

        return $result;
    }

    public function updateUserBaseInfo($where,$value){
        $key    =   $this->autoUidKeyPrefix. 0;
        $result =   Storage::setConditionData($key, $value, $where);
        return $result;
    }

    /**
     * 组装用户基本信息
     * @param unknown $uid
     * @return Ambigous <Ambigous, NULL, boolean, unknown>|string
     */
    public function getUserInfo($uid, $statis= false,$fUid = 0, $checkIsMe = true){
        if (empty($uid)){
            return false;
        }
        $result = $this->diaryListCacheModel->getUserCache($uid);
        if (!empty($result) && count($result) >= 7 && intval($result['update_time']) > 0 && isset($result['sex'])){
            if ((AC::SERVER_TIME - intval($result['update_time'])) > 86400 ){
                $this->diaryListCacheModel->updateUserTime($uid);
            }
            $user = $this->getDefaultUserStruct();
            $user['uid']         =    strval($uid);
            $user['avatar']      =    UK::getuseravatarurl($uid, $result['avatar']);
            $user['background']  =    $this->getUserBackground($result);
            $user['signature']   =    UK::getstr($result['signature'],100,'',1);
            $user['level']       =    strval($result['level']);
            
            $user['account']     =    empty($result['account']) ? ''  : $result['account'];
            $user['tag_list']    =    $this->getUserTagList($result['tags']);
            
            $user['email']       =    empty($result['email'])   ? ''  : $result['email'];
            $user['status']      =    strval($result['status']);
            $user['sex']         =    $result['sex'];
            // 会员信息[是否是会员、是否达人]
            $user['is_vip']      =  $this->isVip($result);
            $user['vip_expire']      =  $result['vip_expire'] ? $result['vip_expire'] : 0;
            $this->judgeVip($user, $uid);
            // 用户字数限制
            $user['is_ability']  = $result['is_ability'];
            $user['ability_level']  = empty($result['ability_level']) ? '0' : strval($result['ability_level']);
            if (empty($result['is_ability']) || intval($result['is_ability']) > 1){
               $user['is_ability']  = '0';
            }
            $user['verified']     = empty($result['verified']) ? '0' : strval($result['verified']);
            $user['max_numbers']  =  $this->maxWordLength($result);
            $user['max_numbers']  =  $user['max_numbers']/2;
            // 调用计数时需要传第二个参数
            if (!empty($statis)){
                $this->addUserCount($result);
            }
            // 禁言用户时间
            $user['gag_time'] = $result['gag_time'];
            if (empty($result['gag_time'])){
                $user['gag_time'] = 0;
            }
            // 昵称判断
            $user['nickname'] = UK::getstr($result['nickname'], 24,'',1);
            if (strlen($user['nickname']) < 1){
            	$user['nickname'] = $result['uid'];
            } 
            // 判断是否关注
            $user['is_followme'] = 0;
            $user['is_mefollow'] = 0;
            if ($fUid > 0){
                $user['is_mefollow'] = $this->checkIsFollow($uid,$fUid);
            }
            
            // 亲加云
            $user['thirdParty'] = array('gotype_token' => $this->getGoTypePwd($uid));
            if ($checkIsMe) {
                $user = $this->checkIsMe($user);
            }
            //订阅号作者认证等级
            $user['subscribe_level'] = !empty($result['verified']) ? 202 : 0;
	    
            //女生认证兼容以前
            $user['sex'] = $this->compatibleSexOfLastVersion($user['sex']);

            return $user;
        }

        $userInfo['userInfo']          =   $this->userModel->getUserInfo($uid);
        $userInfo['userMember']        =   $this->userMemberModel->getMemberInfo(array('uid'=>$uid));
        // 获取达人状态
        $userInfo['ability']           =   $this->userModel->fetchAbility(array('uid'=>$uid));
        // 获取用户状态,如果封禁了则状态为2
		$autoUid					   =   $this->getUserBaseInfo(array('uid'=>$uid));
		$userInfo['userMember']['status'] = $autoUid['status'];
        if (!empty(AC::$errorNo) || empty($userInfo)){
            return false;
        }
        // 组装用户内部调用缓存结构
        $user = $this->rebuildUserInfo($userInfo);
        $this->diaryListCacheModel->addUserCache($user);
        // 更新update_time
        $this->diaryListCacheModel->updateUserTime($uid);
        
        $user['tag_list']    =    $this->getUserTagList($user['tags']);
        unset($user['tags']);
        $user['avatar']      =    UK::getuseravatarurl($uid, $user['avatar']);
        $user['background']  =    $this->getUserBackground($user);
		
        // 会员信息[是否是会员、是否达人]
        $user['is_vip']        =  $this->isVip($user);
        $this->judgeVip($user, $uid);
        // 日记最大发表字数
        $user['max_numbers']  =  $this->maxWordLength($result);
        $user['max_numbers']  =  $user['max_numbers']/2;
        // 调用计数时需要传第二个参数
        if (!empty($statis)){
            $this->addUserCount($user);
        }
        // 昵称判断
        $user['nickname'] = UK::getstr($user['nickname'], 24,'',1);
        if (strlen($user['nickname']) < 1){
        	$user['nickname'] = $user['uid'];
        }
        
        // 判断是否关注
        $user['is_followme'] = 0;
        $user['is_mefollow'] = 0;
        if ($fUid > 0){
            $user['is_mefollow'] = $this->checkIsFollow($uid,$fUid);
        }
        
        // 亲加云
        $user['thirdParty'] = array('gotype_token' => $this->getGoTypePwd($uid));

        if ($checkIsMe) {
            $user = $this->checkIsMe($user);
        }

        //订阅号作者认证等级
        $user['subscribe_level'] = !empty($result['verified']) ? 202 : 0;
	
        //女生认证兼容以前
        $user['sex'] = $this->compatibleSexOfLastVersion($user['sex']);
	
        return $user;
    }
    
    public function compatibleSexOfLastVersion($sex){
    	if($sex == AC::$sex['femaleauth'] && AC::$femaleVersion == 1){
    		return 0;
    	}
    	return $sex;
    }
    
    /**
     * 获取用户标签列表
     * @param unknown $tags
     * @return multitype:|multitype:Ambigous <multitype:, multitype:unknown Ambigous <string, multitype:multitype:string  > >
     */
    private function getUserTagList ($tags) {
        if (empty($tags)) return array();
        
        $tagsArr = array();
        $tag_arr = explode(',', $tags);
        foreach ($tag_arr as $val){
            $tagInfo = Tags::getTagInfo(trim($val));
            if (empty($tagInfo)){
                continue;
            }
            $tagsArr[] = $tagInfo;
        }
        
        return $tagsArr;
    }
    
    /**
     * 获取跟用户关系
     * @param unknown $uid
     * @param unknown $fUid
     * @return number
     */
    private function checkIsFollow($fUid, $uid){
        if (AC::$meFollowUids === NULL){
    	    $uids = $this->followModel->getMeFollowsList($uid);
    	    if (empty($uids)){
    	    	$uids = array();
    	    }
    	    AC::$meFollowUids    =    $uids;
        }
    	if (in_array($fUid, AC::$meFollowUids)){
    		return 1;
    	}
    	return 0;
    }
    
    
    public function getUserList($info)/*{{{*/
    {
        $start  =   0;
        $length =   AC::FETCH_USER_LIST_LEN;
        isset($info['start'])   &&  $start  =   $info['start'];
        isset($info['length'])  &&  $length =   $info['length'];
        if ($start  <   0)  $start  =   0;

        $where  =   NULL;
        if (isset($info['status']))     $where['status']    =   $info['status'];
        if (!empty($info['deviceSN']))  $where['deviceSN']  =   $info['deviceSN'];

        $key    =   $this->autoUidKeyPrefix. 0;
        $orderBy=   ' uid DESC ';
        if (empty($info['fields']))
        {
            $result =   Storage::getConditionManyData($key, $where, $orderBy, $start, $length);
        }
        else
        {
            $result =   Storage::getFieldsConditionManyData($key, $info['fields'], $where, $orderBy, $start, $length);
        }
        return  $result;
    }/*}}}*/

    public function getUserBaseInfoUseLike($info)/*{{{*/
    {
        if (!empty($info['uid']))
        {
            $userBaseInfo   =   $this->getUserBaseInfo(array('uid' => $info['uid']));
            if (empty($userBaseInfo['account'])   ||  empty($info['fields'])) $result =   $userBaseInfo;
            else    $result =   array('uid' =>  $userBaseInfo['uid'], 'nickname' => $userBaseInfo['nickname']);
            $user = $this->getUserInfo($info['uid']);
            if ($user['uid'] < 1){
                return array();
            }
            $result['avatar'] = $user['avatar'];
            $result['user']   = $this->checkIsMe($user);
            
            return  array($result);
        }
        
        if (!empty($info['nickname'])){
            $start  =   0;
            $length =   AC::FEED_LIST_DISPLAY_LEN;
            isset($info['start'])   &&  $start  =   intval($info['start']);
            isset($info['length'])  &&  $length =   intval($info['length']);
            if ($start  <   0)  $start  =   0;            
	    if ($length <=  0)  $length =   AC::FEED_LIST_DISPLAY_LEN;
            
            $result  = array();
            $keyword = $info['nickname'];
            if ($keyword == '%粉粉%' && $start == 0){
                $length--;
                $result[]     =  $this->getUserInfo('1');
            }
            $list = $this->sphinxSearch($keyword, $start, $length);
            if (!empty($list['matches'])){
                foreach ($list['matches'] as $val){
                    $result[] = $this->getUserInfo($val['id']);
                }
            }
            if (empty($list['matches'])){
                return array();
            }
        }
        
        
        return  $result;
    }/*}}}*/
    
    // 搜索
    private function sphinxSearch($keyword, $start, $length){
        $client = RedisPool::initSphinx();
        if (empty($client)) return array();
        // 设置返回数据的排序
        $client->setSortMode(SPH_SORT_ATTR_DESC, 'id');
        // 分页
    
        $client->SetLimits($start, $length, '1000');
        // 搜索,1=日记,2=用户
        $searchd = array(
                '1' => 'hot_main,hot_delta',
                '2' => 'user_main,user_delta',
        );
        return $client->query($keyword, $searchd[2]);
    }
    
    public function checkAccount($account, $registerCheck = FALSE)/*{{{*/
    {
        $key    =   $this->autoUidKeyPrefix. $account;
        $result =   Storage::getData($key);

        if (empty($result['uid']))  return  NULL;
        if ($registerCheck) AC::$errorNo    =   'AUM002';
        return  $result['uid'];
    }/*}}}*/

    public function checkEmail($email, $registerCheck = FALSE)/*{{{*/
    {
        $key    =   $this->autoUidKeyPrefix. 0;
        $where  =   array('email' => $email);
        $result =   Storage::getConditionData($key, $where);

        if (empty($result['uid']))  return  NULL;
        if ($registerCheck) AC::$errorNo    =   'AUM003';
        return  $result['uid'];
    }/*}}}*/

    public function setUserInfo($info)/*{{{*/
    {
        if (empty($info['uid']) ||  empty($info['account']))
        {
            AC::$errorNo    =   'AUM007';
            return  FALSE;
        }
        isset($info['nickname'])&&  $data['nickname']   =   $info['nickname'];
        if (isset($info['email']))
        {
            $data['email']  =   $info['email'];
            $checkEmail     =   $this->checkEmail($info['email'], TRUE);
            if (!empty($checkEmail))    return  FALSE;
        }

        if (empty($data))   return  TRUE;
        $key    =   $this->autoUidKeyPrefix. $info['account'];
        $where  =   array('uid' => $info['uid']);
        $result =   Storage::setConditionData($key, $data, $where);
        
        return  $result;
    }/*}}}*/

    public function modifyUserStatus($info)/*{{{*/
    {
        if (empty($info['uid']))
        {
            AC::$errorNo    =   'AUM010';
            return  FALSE;
        }
        if (!isset($info['status']))
        {
            AC::$errorNo    =   'AUM011';
            return  FALSE;
        }

        $data['status']     =   $info['status'];
        $key    =   $this->autoUidKeyPrefix. 0;
        $where  =   array('uid' => $info['uid']);
        $result =   Storage::setConditionData($key, $data, $where);

        return  $result;
    }/*}}}*/

    public function getDailyUidNum($info)/*{{{*/
    {
        $today  =   date('Ymd', AC::SERVER_TIME);
        if (empty($info['ymd']) ||  $info['ymd'] >  $today) $ymd    =   $today;
        else    $ymd    =   $info['ymd'];
        $time   =   strtotime($ymd) + 86400;

        $key    =   $this->chatModelKeyPrefix. 0;
        $dbSql  =   ' SELECT count(*) as num, FROM_UNIXTIME(`registerTime`, "%Y%m%d") as ymd FROM autoUid_0 WHERE `registerTime` < '. $time. ' GROUP BY ymd ORDER BY ymd DESC LIMIT 60 ';
        $result =   Storage::fetchDbSentence($key, $dbSql, 2);

        return  $result;
    }/*}}}*/
    
    /**
     * 判断是否关注过我
     * 0 表示未关注
     * 1 表示已关注
     * uid    =    当前登录的用户
     * fUid   =    需比较的用户
     * @param unknown $uid
     * @param unknown $fUid
     * @return string
     */
    public function checkUserFans($uid, $fUid){
        if (empty($uid) || empty($fUid)){
            return '0';
        }
        
        $followStatic    =    '0';
        $static          =    $this->diaryListCacheModel->checkIsFans($uid, $fUid);
        if ($static){
            $followStatic=    '1';
        }
        
        return $followStatic;
        
    }
    
    /**
     * 判断是否关注过他
     * 0 表示未关注
     * 1 表示已关注
     * uid    =    当前登录的用户
     * fUid   =    需比较的用户
     * @param unknown $uid
     * @param unknown $fUid
     * @return string
     */
    public function checkUserFollow($uid, $fUid){
        if (empty($uid) || empty($fUid)){
            return '0';
        }
        
        $fansStatic    =    '0';
        $static          =    $this->diaryListCacheModel->checkIsFriend($uid, $fUid);
        
        if ($static){
            $fansStatic  =    '1';
        }
        return $fansStatic;
    }
    
    /**
     * 判断是否被我拉黑
     * 0 表示未被拉黑
     * 1 表示已被拉黑
     * uid    =    当前登录的用户
     * fUid   =    需比较的用户
     * @param unknown $uid
     * @param unknown $fUid
     * @return string
     */
    public function checkUserBlocked($uid, $fUid){
        if (empty($uid) || empty($fUid)){
            return '0';
        }
        
        $blockedStatic    =    '0';
        $static          =    $this->diaryListCacheModel->checkIsBlocked($uid, $fUid);
        
        if ($static){
            $blockedStatic  =    '1';
        }
        return $blockedStatic;
    }
    
    // 判断是否本人登录,不是则删除帐号以及邮箱
    public function checkIsMe($info){
        if (AC::HOST_UID    !== $info['uid']) {
            unset($info['account']);
            unset($info['email']);
            unset($info['thirdParty']);
        }
        return $info;
    }
    
    // 会员判断
    public function isVip($info)/*{{{*/
    {
        if (isset($info['vip_expire']) && $info['vip_expire']>AC::SERVER_TIME){
            return '1';
        }
        return '0';
    }
    // 用户可输入数字限制
    private function maxWordLength($info)/*{{{*/
    {
    	if (intval($info['is_ability']) > 0 || intval($info['verified']) > 0)
    	{
    		return '20000';
    	}
    	return AC::DIARY_DATA_NUMBERS;
    }
    /**
     * 检查用户是否被禁言
     * @param unknown $info
     * @return boolean
     */
    public function checkUserStatus($info){
        if (!empty($info['status']))
        {
            AC::$errorNo    =   'SA007';
            return  FALSE;
        }
        if (!isset($info['gag_time'])){
            return TRUE;
        }
        if ((intval($info['gag_time']) - AC::SERVER_TIME) > 0){
            $gagInfo = $this->diaryListCacheModel->getGagUserCahce($info['uid']);
            // 禁言时间段
            $period = $info['gag_time'] - $gagInfo['time'];
            // 禁言开始时间
            $month  = date("m",$gagInfo['time']);
            $day    = date("d",$gagInfo['time']);
            $time   = ceil($period/(24*60*60));
            AC::$errorMsg   =   '你因违反粉粉用户协议,已于'.$month.'月'.$day.'日被管理员禁言'.$time.'天！';
            AC::$errorNo    =   'AUM015';
            return FALSE;
        }
        return TRUE;
    }
    /**
     * 检查发言间隔时间
     * 5级以下间隔为30秒
     * @param unknown $uid
     * @return boolean
     */
    public function checkUserSpace($uid){
        if (intval($uid) < 0){
            return TRUE;
        }
        $lastComment = $this->diaryListCacheModel->getCommentCheck($uid);
        $lastComment = intval($lastComment);
        $t = time();
        if (AC::$hostUserBaseInfo['level'] <= 8){
            if ($lastComment > 0 && $lastComment > $t - 15  ) {
                AC::$errorMsg   =   '8级及其以下用户15秒内只能回复一次哦，加油升级吧!';
                AC::$errorNo    =   'COC008';
                return  FALSE;
            }
        }else{
            if ($lastComment > 0 && $lastComment > $t - 10  ) {
                AC::$errorMsg   =   '10秒内只能回复一次哦';
                AC::$errorNo    =   'COC008';
                return  FALSE;
            }
        }
        // 判断是否小于5级
        /*if (AC::$hostUserBaseInfo['level'] < 5){
            if ($lastComment > 0 && $lastComment > $t - 8  ) {
                AC::$errorMsg   =   'lv5以下用户8秒内只能回复一次哦，加油升级吧!';
                AC::$errorNo    =   'COC008';
                return  FALSE;
            } 
        }
        if (AC::$hostUserBaseInfo['level'] >= 5 && AC::$hostUserBaseInfo['level'] < 10){
            if ($lastComment > 0 && $lastComment > $t - 7  ) {
                AC::$errorMsg   =   '太频繁了,7秒内只能操作一次哦~';
                AC::$errorNo    =   'COC008';
                return  FALSE;
            }
        }
        if (AC::$hostUserBaseInfo['level'] >= 10 && AC::$hostUserBaseInfo['level'] < 15){
            if ($lastComment > 0 && $lastComment > $t - 6  ) {
                AC::$errorMsg   =   '太频繁了,6秒内只能操作一次哦~';
                AC::$errorNo    =   'COC008';
                return  FALSE;
            }
        }
        if (AC::$hostUserBaseInfo['level'] >= 15){
            if ($lastComment > 0 && $lastComment > $t - 5  ) {
                AC::$errorMsg   =   '太频繁了,5秒内只能操作一次哦~';
                AC::$errorNo    =   'COC008';
                return  FALSE;
            }
        }*/
    }
    
    /**
     * 设置用户头像,只缓存时间戳
     * @param unknown $info
     * @return string|Ambigous <>
     */
    public function setUserImage($account){
    
        $key        =   $this->userLoginKeyPrefix. $account;
        $where      =   array('account' => $account);
        $result     =   Storage::getConditionData($key, $where);
    
        if (!empty($result['image'])){
            return $result['image'];
        }
        return AC::SERVER_TIME;
    }
    
    /**
     * 生成背景缓存,只缓存时间戳
     * @param unknown $uid
     * @return Ambigous <>|string
     */
    
    public function setUserBackground($uid){
        $info = $this->diaryListCacheModel->getUserCache($uid);
        if (!empty($info['background'])){
            return $info['background'];
        }
        return  AC::SERVER_TIME;
    }
    //获取用户背景
    public function getUserBackground($info){
        
        $base   =  AC::getProtocolUriByOS(AC::$cdn_url_icon);
        if (!preg_match("/\//", $info['background'])){
            $mded   =  strtoupper(md5($info['uid']));
            $len    =  strlen($mded);
             
            $result =  "/".substr($mded, $len-6, 2)."/";
            $result =  $result.substr($mded, $len-4, 2)."/";
            $result =  $result.substr($mded, $len-2, 2)."/".$info['uid']."/background.png!default?";
             
            $result =  $base.$result;
            $hashId =  substr(md5($info['background']), -5);
            
            return $result.$hashId;
        }
        
        $result =  $base.$info['background'];
        return  $result;
    }
    

    /**
     * uid等于日记主人,fUid等于当前登录用户
     * @param unknown $info
     * @param int $fUid
     * @param uid为被查找用户  fUid为本人  nickname为被查找用户的昵称(无备注时返回)
     * @return Ambigous <unknown, Ambigous>
     */
    public function getRemarkName($info,$fUid=NULL){
    	$info['fUid']      =  AC::HOST_UID;
    	if (!empty($fUid)){
    		$info['fUid']  =  $fUid;
    	}
    	
    	if (($info['uid'] == $info['fUid']) || empty($info['fUid'])){
    		return $info['nickname'];
    	}
    	// redis判断是否好友
    	$status =  $this->diaryListCacheModel->checkIsFriend($info['fUid'], $info['uid']);
    	if (!$status){
    		return $info['nickname'];
    	}
    	return $this->changeRmarkName($info);
    }
    /**
     * 判断关系获取备注名
     * @param unknown $info
     * @return unknown|Ambigous <>
     */
    private function changeRmarkName($info){
    	// TODO 获取缓存,没有则从数据库获取;
    	$rMarkInfo    =    $this->diaryListCacheModel->getRmask($info['fUid'],$info['uid']);
    	if (!empty($rMarkInfo)){
    		$rMarkInfo    =    json_decode($rMarkInfo,true);
    		if (!empty($rMarkInfo['r'])){
    			return $rMarkInfo['r'];
    		}
    	}
    	$where = array('uid'=>$info['fUid'],'fUid'=> $info['uid'],'type'=>$this->meFollowType);
    	$key   = $this->followKeyPrefix.$info['fUid'];
    	$result = Storage::getConditionData($key, $where);
    
    	if (empty($result['remark_name'])){
    		return $info['nickname'];
    	}
    	$data = json_encode(array('r'=>$result['remark_name']));
    	$this->diaryListCacheModel->addRmask(AC::HOST_UID,$info['uid'], $data);
    
    	return $result['remark_name'];
    }

    public function getRemarkFromMysql($host_uid, $uid)
    {
        $where = array('uid'=> $host_uid,'fUid'=> $uid,'type'=> 2);
        $key   = $this->followKeyPrefix.$uid;
        $result = Storage::getConditionData($key, $where);
        if (empty($result['remark_name'])) return '';

        return $result['remark_name'];
    }
    
    /**
     * 获取用户金币余额
     * @return number
     */
    public function getUserCoinInfo(){
        $totalCoin = 0;
    
        $api      = UK::getMallApi(AC::HOST_UID);
        $userCoin = $api->getUserCoin();
        if (!empty($userCoin)){
            $totalCoin = $userCoin['balance'];
        }
        return $totalCoin;
    }
    
    // 重构用户基本信息
    public function rebuildUserInfo($userInfo){
        $user = $this->getDefaultUserStruct();
        $user['uid']               =            intval($userInfo['userInfo']['uid']) > 0 ? strval($userInfo['userInfo']['uid']) : '0' ;
        $user['nickname']          =            empty($userInfo['userInfo']['nickname']) ? '' : $userInfo['userInfo']['nickname'];
        
        if ($userInfo['userInfo']['avatar']){
            $user['avatar']        =        	$userInfo['userInfo']['avatar'];
        }else{
            $user['avatar']        =            $this->setUserImage($userInfo['userInfo']['account']);
        }
        if ($userInfo['userInfo']['background']){
            $user['background']        =        $userInfo['userInfo']['background'];
        }else{
            $user['background']        =        $this->setUserBackground($user['uid']);
        }
        $user['signature']         =            empty($userInfo['userInfo']['signature']) ? '' : $userInfo['userInfo']['signature'];
        $user['level']             =            empty($userInfo['userMember']['level']) ? '0'  : strval($userInfo['userMember']['level']);
        $gag_time                  =            $this->diaryListCacheModel->getGagUserCahce($user['uid'] );
        $user['gag_time']          =            intval($gag_time['gag_time']);
        $user['account']           =            empty($userInfo['userInfo']['account']) ? ''  : $userInfo['userInfo']['account'];
        $user['tags']              =            empty($userInfo['userInfo']['tags'])   ? ''  : strval($userInfo['userInfo']['tags']);
        $user['email']             =            empty($userInfo['userInfo']['email'])   ? ''  : $userInfo['userInfo']['email'];
        $user['is_ability']        =            empty($userInfo['ability'][0]['status'])   ? '0'  : $userInfo['ability'][0]['status'];
        if (intval($user['is_ability']) > 1){
            $user['is_ability']    =  '0';
        }
        $user['ability_level']     =         	empty($userInfo['ability'][0]['medal_id'])   ? '0'  : strval($userInfo['ability'][0]['medal_id']);
        $user['verified']          =            empty($userInfo['ability'][0]['verified'])   ? '0'  : $userInfo['ability'][0]['verified'];
        $user['status']            =            intval($userInfo['userMember']['status']) > 0 ? strval($userInfo['userMember']['status']) : '0';
        $user['sex']	           =		isset($userInfo['userInfo']['sex']) ? $userInfo['userInfo']['sex']: '0';
        $user['is_vip']	           =		isset($userInfo['userInfo']['vip']) ? (AC::SERVER_TIME>$userInfo['userInfo']['vip'] ? '0' : '1' ) : '0';
        $user['vip_expire']	       =		isset($userInfo['userInfo']['vip']) ? $userInfo['userInfo']['vip'] : '0';
        return $user;
    }
   
    // 组装用户计数
    public function addUserCount(&$user){
        $userInfo    =   $this->userStatisticsModel->getUserStatistics($user);
        $user['diarys_count']      =            empty($userInfo['diaryTimes']) ? '0'  : strval($userInfo['diaryTimes']);
        $user['comments_count']    =            empty($userInfo['commentTimes']) ? '0'  : strval($userInfo['commentTimes']);
        $user['followMes_count']   =            empty($userInfo['followMeTimes']) ? '0'  : strval($userInfo['followMeTimes']);
        $user['meFollows_count']   =            empty($userInfo['meFollowTimes']) ? '0'  : strval($userInfo['meFollowTimes']);
        $user['likes_count']       =            empty($userInfo['likeTimes']) ? '0'  : strval($userInfo['likeTimes']);
    }
    
    /**
     * 获取手机号验证码
     * @param unknown $uid
     * @param unknown $phone
     * @return boolean|Ambigous <multitype:, unknown, boolean>
     */
    public function getMobileCodeInfo($phone, $codeType) {
        if (empty($phone) || empty($codeType)) {
            AC::$errorNo    =   'AUM005';
            return FALSE;
        }
        
        $key   	   =   $this->mobileCodeKeyPrefix. 0;
        $where     =   array('phone' => $phone, 'type' => $codeType);
        $orderBy   =   " id DESC ";
        $result	   =   Storage::getConditionManyData($key, $where, $orderBy);
        if (empty($result)) return array();
        
        return $result[0];
    }

    /**
     * 获取手机号验证码
     */
    public function getEmailCodeInfo($email, $codeType) {
        if (empty($email) || empty($codeType)) {
            AC::$errorNo    =   'AUM005';
            return FALSE;
        }

        $key   	   =   $this->emailCodeKeyPrefix. 0;
        $where     =   array('email' => $email, 'type' => $codeType);
        $orderBy   =   " id DESC ";
        $result	   =   Storage::getConditionManyData($key, $where, $orderBy);
        if (empty($result)) return array();

        return $result[0];
    }
    
    /**
     * 获取验证码列表
     * @param unknown $ip
     * @param number $start
     * @param unknown $length
     * @return boolean|multitype:|Ambigous <unknown, boolean, multitype:>
     */
    public function getMobileCodes($ip, $start = 0, $length = AC::CODENUMDAILY) {
        if (empty($ip)) {
            AC::$errorNo    =   'AUM005';
            return FALSE;
        }
    
        $key   	   =   $this->mobileCodeKeyPrefix. 0;
        $where     =   array('ip' => $ip);
        $orderBy   =   " time DESC ";
        $result	   =   Storage::getConditionManyData($key, $where, $orderBy, $start, $length);
        if (empty($result)) return array();
    
        return $result;
    }

    /**
     * 获取邮箱验证码列表
     * @param unknown $ip
     * @param number $start
     * @param unknown $length
     * @return boolean|multitype:|Ambigous <unknown, boolean, multitype:>
     */
    public function getEmailCodes($ip, $start = 0, $length = AC::CODENUMPERHOUR) {
        if (empty($ip)) {
            AC::$errorNo    =   'AUM005';
            return FALSE;
        }

        $key   	   =   $this->emailCodeKeyPrefix. 0;
        $where     =   array('ip' => $ip);
        $orderBy   =   " time DESC ";
        $result	   =   Storage::getConditionManyData($key, $where, $orderBy, $start, $length);
        if (empty($result)) return array();

        return $result;
    }
    
    /**
     * 初始化记录
     * @param unknown $uid
     * @param unknown $phone
     * @param unknown $code
     * @return boolean|Ambigous <unknown, boolean, number, resource>
     */
    public function addMobileCode($mobile, $codeType, $code, $uid = 0) {
        if (empty($mobile) || empty($code) || empty($codeType)) {
            AC::$errorNo    =   'AUM005';
            return FALSE;
        }
    
        $key   	   =   $this->mobileCodeKeyPrefix. 0;
        $data      =   $this->assembleMobileCodeDataOfMysql($uid, $mobile, $code, $codeType);
        $result	   =   Storage::addData($key, $data);
        return $result;
    }

    public function addEmailCode($email, $codeType, $code, $uid = 0) {
        if (empty($email) || empty($code) || empty($codeType)) {
            AC::$errorNo    =   'AUM005';
            return FALSE;
        }

        $key   	   =   $this->emailCodeKeyPrefix. 0;
        $data      =   $this->assembleEmailCodeDataOfMysql($uid, $email, $code, $codeType);
        $result	   =   Storage::addData($key, $data);
        return $result;
    }
    
    /**
     * 更新手机号验证码
     * @param unknown $uid
     * @param unknown $phone
     * @return boolean|Ambigous <boolean, unknown, number, resource>
     */
    public function setMobileCode($mobile, $codeType, $code) {
        if (empty($mobile) || empty($code) || empty($codeType)) {
            AC::$errorNo    =   'AUM005';
            return FALSE;
        }
    
        $key   	   =   $this->mobileCodeKeyPrefix. 0;
        $where     =   array('phone' => $mobile, 'type' => $codeType);
        $data      =   array('code' => $code, 'time' => AC::SERVER_TIME);
        $result	   =   Storage::setConditionData($key, $data, $where);
        return $result;
    }

    /**
     * 手机号验证码置为已使用
     * @return boolean|Ambigous <boolean, unknown, number, resource>
     */
    public function setMobileCodeUesd($where, $data) {    
        $key       =   $this->mobileCodeKeyPrefix. 0;
        $result    =   Storage::setConditionData($key, $data, $where);
        return $result;
    }
    
    /**
     * 校验验证码是否合法
     * @param unknown $phone
     * @param unknown $code
     * @return boolean
     */
    public function checkMobileCodeIsValid($phone, $code, $codeType) {
        if (empty($phone) || empty($code) || empty($codeType)) {
            AC::$errorNo    =   'AUM005';
            return FALSE;
        }
        $key = $this->mobileCodeKeyPrefix. 0;
        $codeInfo = $this->getMobileCodeInfo($phone, $codeType);
        if (empty($codeInfo) || ($code != $codeInfo['code'])) {
            AC::$errorMsg= '该验证码错误，请重新验证~';
            AC::$errorNo = 'AUM005';
            return false;
        }
        
        if ($codeInfo && ((AC::SERVER_TIME - $codeInfo['time']) > AC::CODEEXPIRE)) {
            AC::$errorMsg= '该验证码已失效，请重新验证~';
            AC::$errorNo = 'AUM008';
            return false;
        }

        if ($codeInfo['status'] == 1) {
            AC::$errorMsg= '该验证码已失效，请重新验证~';
            AC::$errorNo = 'AUM008';
            return false;
        }

        /*$where     =   array('id' => $codeInfo['id']);
        $data      =   array('status' => 1);
        $this->setMobileCodeUesd($where, $data);*/
        return true;
    }

    /**
     * 校验邮箱验证码是否合法
     */
    public function checkEmailCodeIsValid($email, $code, $codeType) {
        if (empty($email) || empty($code) || empty($codeType)) {
            AC::$errorNo    =   'AUM005';
            return FALSE;
        }

        $codeInfo = $this->getEmailCodeInfo($email, $codeType);
        if ($codeInfo && ((AC::SERVER_TIME - $codeInfo['time']) > AC::CODEEXPIRE)) {
            AC::$errorMsg= '该验证码已失效，请重新验证~';
            AC::$errorNo = 'AUM008';
            return false;
        }

        if (empty($codeInfo) || ($code != $codeInfo['code'])) {
            AC::$errorMsg= '该验证码错误，请重新验证~';
            AC::$errorNo = 'AUM005';
            return false;
        }

        return true;
    }
    
    private function assembleMobileCodeDataOfMysql ($uid, $phone, $code, $type = 0) {
        if (empty($phone) || empty($code)) {
            return false;
        }
        
        $data = array(
            'uid'   =>  $uid,
            'phone' =>  $phone,
            'code'  =>  $code,
            'type'  =>  $type,
            'area'  =>  '86',
            'ip'    =>  UK::getClientIp(),
            'time'  =>  AC::SERVER_TIME
        );
        
        return $data;
    }

    private function assembleEmailCodeDataOfMysql ($uid, $email, $code, $type = 0) {
        if (empty($email) || empty($code)) {
            return false;
        }

        $data = array(
            'uid'   =>  $uid,
            'email' =>  $email,
            'code'  =>  $code,
            'type'  =>  $type,
            'ip'    =>  UK::getClientIp(),
            'time'  =>  AC::SERVER_TIME
        );

        return $data;
    }
    
    /**
     * 更新最后用户活动时间
     * 
     * @param unknown $user
     */
    public function updateUserLastActivity($uid){  
        if (empty($uid)) {
            return FALSE;
        }  		
        $result = $this->diaryListCacheModel->getUserStatus($uid);
        $last = intval($result['la_act']);
        // 小于一天活跃时间更新
        if($last < AC::SERVER_TIME - 86400){
            $this->diaryListCacheModel->setUserStatus($uid, array("la_act"=>AC::SERVER_TIME));
        }
        
        // 活跃时间小于5天，时间线和动态时间线重建
        if ($last < AC::SERVER_TIME - 432000){
            RedisPool::addGearmanJob("timeline",      array("uid" => $uid), $uid);
            RedisPool::addGearmanJob("feed_timeline", array("uid" => $uid), $uid);
            RedisPool::addGearmanJob("feedme_timeline", array("uid" => $uid), $uid);
        }

        /*// 在5天以内的活跃用户去重建数据
        if ($last > AC::SERVER_TIME - 86400 * 5){
            RedisPool::addGearmanJob("activity_timemchine", array("uid" => $uid), $uid);
        }*/
    }
    
    /**
     * 达人升级
     * @param unknown $uid
     * @return boolean|Ambigous <multitype:, unknown, boolean, mixed>
     */
    public function updateAbilityLevel ($uid) {
        if (intval($uid) < 1 ){
            return FALSE;
        }
        
        $userInfo = $this->getUserInfo($uid);
        if (empty($userInfo) || intval($userInfo['is_ability']) != 1) {
            return FALSE;
        }
        
        $level         = $userInfo['level'];
        $ability_level = $userInfo['ability_level'];
        
        $userStatistics   =   $this->userStatisticsModel->getUserStatistics(array('uid' => $uid));
        $fans          = $userStatistics['followMeTimes'];
        $diarytimes    = $userStatistics['diaryTimes'];
        $likedtimes    = $userStatistics['likeMeTimes'];
        $topictimes    = $userStatistics['topicTimes'];
        
        $newLevel = $this->checkAbilityNewLevel($level, $fans, $diarytimes, $likedtimes, $topictimes, $ability_level);
        if (intval($ability_level) != $newLevel) {
            $this->userModel->setAbilityLevel($uid, $newLevel);
            $this->diaryListCacheModel->updateUserAbilityLevel($uid, $newLevel);
        }
        
        return TRUE;
    }
    
    private function checkAbilityNewLevel ($level = 1, $fans = 0, $diarytimes = 0, $likedtimes = 0, $topictimes = 0, $ability_level = 0) {
        $levelConfig = array(
                1    =>    array('level' => 12, 'fans' => 50,     'diarytimes' => 50,   'likedtimes' => 20,     'topictimes' => 0),
                2    =>    array('level' => 20, 'fans' => 1000,   'diarytimes' => 200,  'likedtimes' => 500,    'topictimes' => 20),
                3    =>    array('level' => 30, 'fans' => 3000,   'diarytimes' => 1000, 'likedtimes' => 1000,   'topictimes' => 50),
                4    =>    array('level' => 40, 'fans' => 8000,  'diarytimes' => 3000, 'likedtimes' => 5000,   'topictimes' => 200),
                5    =>    array('level' => 50, 'fans' => 20000,  'diarytimes' => 5000, 'likedtimes' => 20000,  'topictimes' => 500)
        );
        
        $newLevel = 0;
        foreach ($levelConfig as $key => $value) {
            if ($level >= $value['level'] && $fans >= $value['fans'] && $diarytimes >= $value['diarytimes'] && $topictimes >= $value['topictimes'] ) {
                $newLevel = $key;
            }else{
                break;
            }
        }
        
        if ($newLevel <= $ability_level) {
            $newLevel = $ability_level;
        }
        
        return $newLevel;
    }
    
    public function rebuildUserFollowersAndFansList ($uid) {
        $user_flush_time_cache = $this->diaryListCacheModel->getUserFlushTimeCache($uid);
        if (intval($user_flush_time_cache['rs_t']) < (AC::SERVER_TIME - 86400)) {
            $data = array('rs_t' => AC::SERVER_TIME);
            $this->diaryListCacheModel->updateUserFlushTimeCache($uid, $data);
            $this->userStatisticsModel->rebuildUserFollow(array('uid' => $uid));
        }
        return TRUE;
    }
    
    public function unsetOpenAccountField (&$info) {
        if (strpos('a'.$info['account'], 'open-qq-') == 1){
            unset($info['account']);
        }
        if (strpos('a'.$info['account'], 'open-weibo-') == 1){
            unset($info['account']);
        }
        if (strpos('a'.$info['account'], 'open-wechat-') == 1){
            unset($info['account']);
        }
        if (strpos('a'.$info['account'], 'mobile-') == 1){
            unset($info['account']);
        }
        return $info;
    }
    
    public function checkIsOpenAccount ($account) {
        if (strpos('a'.$account, 'open-qq-') == 1 || strpos('a'.$account, 'open-weibo-') == 1 || strpos('a'.$account, 'open-wechat-') == 1) {
            return true;
        }
        
        return false;
    }
    
    private function getDefaultUserStruct(){
        $user = array();
        $user['uid']          =  "0";
        $user['nickname']     =  "";         // 昵称判断
        $user['signature']    =  "";
        $user['avatar']       =  "";
        $user['background']   =  "";
        $user['level']        =  "0";
        $user['gag_time']     =  "0";       // 禁言用户时间
        $user['max_numbers']  =  "2000";    // 会员信息[是否是会员、是否达人]
        $user['is_vip']       =  "0";       // 会员信息[是否是会员、是否达人]
        $user['vip_expire']       =  "0";       // 会员过期时间
        $user['is_ability']   =  "0";
        $user['ability_level']=  "0";
        $user['verified']     =  "0";
        $user['is_followme']  =  "0";
        $user['is_mefollow']  =  "0";
        $user['account']      =  "";
        $user['email']        =  "";
        $user['status']       =  "0";
        $user['sex']	      =  "0";
        return $user;
    }

    // =============================================Greaman任务===================================================
    
    // 亲加云密码
    public function getGoTypePwd ($uid) {
        if (empty($uid)) {
            return '';
        }
    
        // 该算法属于保密算法(包括key),仅允许服务端使用,客户端不可见.一旦泄露必须重新生成修改第三方上(亲加)粉粉帐号的密码.
        $password = md5($uid."gotye"."73g8e8xi1sse");
        return $password;
    }

    // 发短信
    public function sendShortMessage($param) {
        $data = array(
            "content" => $param['content'],  // 短信内容
            "mobile" => strval($param['mobile']),  // 手机号(18964729597)，多个用逗号分隔
            "time" => AC::SERVER_TIME,
            "ext"   =>  ($param['appname'] == '可萌记账') ? '1' : ''
        );
        
        return $this->sendShortMsgJob("SendSms", $data);
    }

    // 发短信队列
    private function sendShortMsgJob($task,  $data){
        $json = UK::JsonFormat($data);
        return RedisPool::doBackgroundGearmanJob("pinksms_".$task, $json);
    }

    public function addUserVip($info, $uid){
        $new = [
            'uid' => $uid,
            'start_time' => AC::SERVER_TIME,
            'end_time' => $info['end_time'],
            'yearvip_end_time' => isset($info['yearvip_end_time']) ? $info['yearvip_end_time'] : 0,
            'type' => intval($info['type']),
            'follow_rule' => 0,
            'diy_source' => '',
            'status' => 0,
            'extra' => isset($info['extra']) ? $info['extra'] : ''
        ];
        $key = $this->userVipKeyPrefix. 0;
        $item = Storage::getConditionData($key, [ 'uid'=>$uid ]);
        if ($item){
            //以前开通过会员
            unset($new['uid']);
            $result = $this->updateUserVipInfo($new, $uid);
        }else{
            $result = Storage::addData($key, $new);
        }
        return $result;
    }

    public function getUserVipInfo($uid){
        if (isset(self::$_G['vip'][$uid]))return self::$_G['vip'][$uid];//一次请求中多次执行该方法只会查询一次
        $key = $this->userVipKeyPrefix. 0;
        $result = Storage::getConditionData($key, [ 'uid'=>$uid, 'status'=>0 ]);
        if ($result && AC::SERVER_TIME>$result['end_time']){
            //vip 已过期
            //$this->updateUserVipInfo(['status'=>1], $uid);
            $result = [];
        }
        if (empty($result)){
            $result = [];
        }else{
            $result['is_year_vip'] = $result['yearvip_end_time'] > AC::SERVER_TIME ? '1' : '0';
        }
        self::$_G['vip'][$uid] = $result;
        return $result;
    }

    public function updateUserVipInfo($set, $uid){
        $key = $this->userVipKeyPrefix. 0;
        $result = Storage::setConditionData($key, $set, [ 'uid'=>$uid ]);
        return $result;
    }

    public function judgeVip(&$user, $uid){
        if ($user['is_vip']){
            $vip_info = $this->getUserVipInfo($uid);
            if (empty($vip_info)){
                $user['is_vip'] = '0';
                $user['is_year_vip'] = '0';
            }else{
                unset($vip_info['extra']);
                $user['is_year_vip'] = $vip_info['is_year_vip'];
                $user['vip_info'] = $vip_info;
            }
        }
    }
}

